using System;
namespace MuYue.Common
{
	public class SortedBTree<T> where T : TreeNode
	{
		private TreeNode treeRoot;
		private readonly object treeLock = new object();
		public int NodeNumber
		{
			get;
			set;
		}
		public int Dequene(T node)
		{
			int result;
			lock (this.treeLock)
			{
				this.AddNode(node);
				result = this.NodeNumber++;
			}
			return result;
		}
		public T Enquene(out int num)
		{
			T node;
			lock (this.treeLock)
			{
				num = this.NodeNumber;
				node = this.GetNode();
			}
			return node;
		}
		private void AddNode(TreeNode node)
		{
			if (this.treeRoot == null)
			{
				this.treeRoot = node;
				return;
			}
			TreeNode treeNode = this.treeRoot;
			TreeNode treeNode2 = null;
			int num = 0;
			while (treeNode != null)
			{
				treeNode2 = treeNode;
				num = treeNode.CompareTo(node);
				treeNode = ((num > 0) ? treeNode2.LeftNode : treeNode2.RightNode);
			}
			if (num > 0)
			{
				treeNode2.LeftNode = node;
			}
			else
			{
				treeNode2.RightNode = node;
			}
			node.FatherNode = treeNode2;
		}
		private T GetNode()
		{
			TreeNode leftNode = this.treeRoot;
			if (leftNode != null)
			{
				while (leftNode.LeftNode != null)
				{
					leftNode = leftNode.LeftNode;
				}
			}
			this.DeleteNode(leftNode);
			return leftNode as T;
		}
		private void DeleteNode(TreeNode waitfotDel)
		{
			if (waitfotDel == null)
			{
				return;
			}
			if (waitfotDel.FatherNode == null)
			{
				if (waitfotDel.RightNode != null)
				{
					waitfotDel.RightNode.FatherNode = null;
				}
				this.treeRoot = waitfotDel.RightNode;
			}
			else
			{
				waitfotDel.FatherNode.LeftNode = waitfotDel.RightNode;
				if (waitfotDel.FatherNode.LeftNode != null)
				{
					waitfotDel.FatherNode.LeftNode.FatherNode = waitfotDel.FatherNode;
				}
			}
			this.NodeNumber--;
		}
	}
}
